<?php 
class XmlController extends Zend_Controller_Action{
	public function array_to_xml($sourArray, &$xml) {
		foreach($sourArray as $key => $value) {
			if(is_array($value)) {
				if(!is_numeric($key)){
					$subnode = $xml->addChild("$key");
					$this->array_to_xml($value, $subnode);
				}
				else{
					$subnode = $xml->addChild("item");
					$this->array_to_xml($value, $subnode);
				}
			}
			else {
				$xml->addChild("$key",htmlspecialchars("$value"));
			}
		}
	}
	public function init(){
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$this->response = $this->getResponse();
		$this->response->setHeader('Content-type', 'application/xml;charset=UTF-8', true);
		
		$this->response->setHeader('Access-Control-Allow-Origin', '*');
		
		$this->response->setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
		$this->response->setHeader('Access-Control-Allow-Headers', 'Content-Type');
		
	}
	// disable layout
	public function indexAction(){
		$table 		= $this->_request->getParam("table","grammar");
		$curentCid 	= $this->_request->getParam("cid","0");
		$modelClass = 'Default_Model_'.ucfirst($table);
		
		$mModel 		= new $modelClass();
		$data 			= $mModel->listItems(array('cid'=>$curentCid));
		$xml 			= new SimpleXMLElement("<?xml version=\"1.0\"?><".$table."></".$table.">");
		//"lesson","kanji","vocabulary","listening","grammar","question","reading"

		$fieldsArray = array(
				'lesson'=>'le_id,le_title,le_dataversion_id',
				'kanji'=>'k_id,k_kanji,k_mean_kanji,k_mean_en,k_mean_vi,k_onyomi,k_kunyomi,k_remember,k_on_ex,k_kun_ex,k_dataversion_id',
				'vocabulary'=>'v_id,v_word,v_hiragana,v_mean_kanji,v_mean_en,v_mean_vi,v_lesson_id,v_note,v_dataversion_id',
				'listening'=>'li_id,li_lesson_id,li_title,li_thumb,li_script_jp,li_script_en,li_script_vi,li_track,li_dataversion_id',
				'grammar'=>'g_id,g_title,g_mean,g_explain,g_note,g_example_jp,g_example_en,g_example_vi,g_lesson_id,g_dataversion_id',
				'question'=>'q_id,q_question,q_answer1,q_answer2,q_answer3,q_answer4,q_correct,q_type,q_lesson_id,q_dataversion_id',
				'reading'=>'r_id,r_title,r_content_jp,r_content_en,r_content_vi,r_lesson_id,r_dataversion_id',
				'testtype'=>'t_id,t_type,t_dataversion_id',
		);
		$data['fields'] = $fieldsArray[$table];
		$data['tableName'] = $table;
		
		$this->array_to_xml($data,$xml);
		$xmltext = $xml->asXML();
		$this->filter($xmltext);
		$this->response->setBody($xmltext);
	}
	public static function filter(&$subject){
		$subject = str_replace('\"', '"', $subject);
		//$subject = str_replace('"', "|||", $subject);
	}
	public static function filter2($subject){
		return $subject = str_replace('"', "rpl01", $subject);
		//$subject = str_replace('"', "|||", $subject);
	}

	// function defination to convert array to xml
	
}